/*
 * @lc app=leetcode.cn id=304 lang=cpp
 *
 * [304] 二维区域和检索 - 矩阵不可变
 */
#include "include.h"
// @lc code=start
class NumMatrixTest {
public:
    NumMatrixTest(vector<vector<int>>& matrix) {
        m = matrix.size();
        n = matrix[0].size();
        // dummy / vertual edge
        sum_ = new int[(m+1)*(n+1)];
        memset(sum_, 0, (m+1)*(n+1)*sizeof(int));
        // mat :
        // a b
        // c d
        // sum :
        // a    ab
        // ac   abcd
        // abcd = ab + ac + d - a
        for (int i=0;i<m;i++){
            for (int j=0;j<n;j++){
                // sum_[(i+1)*(n+1)+(j+1)] ????????
                sumMatix(i, j) = sumMatix(i,j-1)+sumMatix(i-1,j)
                                -sumMatix(i-1,j-1)+matrix[i][j];
            }
        }
        // show
        // printf("------------------\n");
        // for (int i=0;i<m+1;i++){
        //     for (int j=0;j<n+1;j++){
        //         printf("%3d ", sum_[i*(n+1)+j]);
        //     }
        //     printf("\n");
        // }
        // printf("------------------\n");
    }
    // ~NumMatrix(){
    //     delete sum_;
    // }
    int sumRegion(int row1, int col1, int row2, int col2) {
// printf("%3d = %3d (%d %d) - %3d - %3d + %3d (%d %d)\n", 
// sumMatix(row2,col2)-sumMatix(row2,col1-1)-sumMatix(row1-1,col2)+sumMatix(row1-1, col1-1),
// sumMatix(row2,col2), row2,col2,
// sumMatix(row2,col1-1),
// sumMatix(row1-1,col2),
// sumMatix(row1-1,col1-1), row1-1,col1-1
// );
        return sumMatix(row2,col2)-sumMatix(row2,col1-1)-sumMatix(row1-1,col2)+sumMatix(row1-1, col1-1);
    }
private:
    int m, n;
    int* sum_;
    inline int& sumMatix(int row, int col){
        return sum_[(row+1)*(n+1)+(col+1)];
    }
};

/**
 * Your NumMatrix object will be instantiated and called as such:
 * NumMatrix* obj = new NumMatrix(matrix);
 * int param_1 = obj->sumRegion(row1,col1,row2,col2);
 */
// @lc code=end

